package com.tlkj.common.curd.util;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyBatisSqlRegexExtractor {

    public static void main(String[] args) {
        String dynamicSql = "SELECT * FROM devops_api " +
                "WHERE 1=1 " +
                "<if test=\"id != null\"> AND id=#{id} </if> " +
                "<if test=\"menuIds != null\"> AND menu_id IN " +
                "<foreach collection=\"menuIds\" item=\"menuId\" open=\"(\" separator=\",\" close=\")\"> " +
                "#{menuId} " +
                "</foreach> " +
                "</if>";

        Set<String> parameters = extractParameters(dynamicSql);

        System.out.println("Parameters: " + parameters);
    }

    public static Set<String> extractParameters(String dynamicSql) {
        Set<String> parameters = new HashSet<>();

        // 匹配 #{parameter} 或 ${parameter}
        Pattern pattern = Pattern.compile("[#|$]\\{([^}]*)}");
        Matcher matcher = pattern.matcher(dynamicSql);

        while (matcher.find()) {
            parameters.add(matcher.group(1).trim());
        }

        // 匹配 <foreach collection="collectionName" ...>
        pattern = Pattern.compile("<foreach(?:\\s+(?!collection)[^>]*)*\\s+collection=\"([^\"]+)\"");
        matcher = pattern.matcher(dynamicSql);

        while (matcher.find()) {
            parameters.add(matcher.group(1).trim());
        }
        // 匹配 <foreach item="itemName" ...>
        pattern = Pattern.compile("<foreach(?:\\s+(?!item)[^>]*)*\\s+item=\"([^\"]+)\"");
        matcher = pattern.matcher(dynamicSql);

        while (matcher.find()) {
            parameters.remove(matcher.group(1).trim());
        }

        return parameters;
    }
}
